package com.chy.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chy.common.JwtUtil;
import com.chy.common.R;
import com.chy.common.Utils;
import com.chy.entity.User;
import com.chy.entity.UserInfo;
import com.chy.service.UserInfoService;
import com.chy.service.UserService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CacheManager cacheManager;

    /**
     * 查询用户
     */
    @PostMapping("/getUser")
    public R<User> getUser(@RequestBody User user){
        User ones = userService.getById(user.getId());
        if(ones == null){
            return R.success("用户不存在");
        }else {
            return R.success(ones);
        }
    }
    /**
     * 查询用户详情
     */
//    @Cacheable(value = "userData", key = "#userInfo.id", unless = "#result.data == null")
    @PostMapping("/getUserInfo")
    public R<UserInfo> getUserInfo(@RequestBody UserInfo userInfo){
//        System.out.println("----------------");
//        System.out.println(userInfo);
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getId, userInfo.getId());
        UserInfo one = userInfoService.getOne(wrapper);
        if(one == null){
            return R.success("用户不存在");
        }else {
            return R.success(one);
        }
    }

    /**
     * 更新用户
     */
    @PostMapping("/updateUser")
    public R<String> updateUser(@RequestBody Map<String, Object> params) {
        return userService.updateUser(params);
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    @Transactional
    public R<String> deleteUser(@RequestBody List<Map<String, Object>> list) {
        Boolean flag = userService.deleteByIds(list);
        return flag? R.success() : R.error();
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public R<String> register(@RequestBody Map<String, Object> params){

        return userService.createNewUser(params);
    }


    @PostMapping("/addUser")
    public R<String> addUser(@RequestBody Map<String, Object> params) {
        return userService.createNewUser(params);
    }

    /**
     * 登录
     */
//    @CachePut(value = "userData", key = "#result.data.id")
    @PostMapping("/login")
    public R<HashMap<String, Object>> login(HttpServletRequest request, @RequestBody User user){

        if(user.getName() == null || user.getPassword() == null){
            return R.error("用户名或密码不能为空！");
        }

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName, user.getName());
        User one = userService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(one == null){
            return R.error("无此用户！");
        }

        //1、将页面提交的密码password进行md5加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //4、密码比对，如果不一致则返回登录失败结果
        if(!one.getPassword().equals(password)){
            return R.error("密码错误！");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(one.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6、登录成功，生成token并存入redis中
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("name", one.getName());
        claims.put("id", String.valueOf(one.getId()));
        claims.put("admin", String.valueOf(one.getIsAdmin()));
        claims.put("superAdmin", String.valueOf(one.getIsSuperAdmin()));
        String token = JwtUtil.createJWT(claims, 30*60*1000L);  // 登录后30分钟过期
//        Claims jwt = JwtUtil.verifyJwt(token);
//        System.out.println(jwt);
//        System.out.println(token);
        redisTemplate.boundValueOps(String.valueOf(one.getId())).set(token, 30, TimeUnit.MINUTES);

//        request.getSession().setAttribute("user", one.getId());

        HashMap<String, Object> res = Utils.ObjectToMap(one);

        res.put("token", token);

        return R.success(res, "登录成功");
    }

    /**
     * 员工退出登录
     */
    @PostMapping("/logout")
    public R<String> logout(@RequestBody Map<String, Object> params){
        //清理Session中保存的当前登录员工的id
//        request.getSession().removeAttribute("user");
        redisTemplate.delete(params.get("id"));
        return R.success("退出登录成功");
    }

    @PostMapping("/list")
    public R<Page> Page(@RequestBody Map<String, Object> params) {
        Page pageInfo = userService.selectByPage(params);
        return R.success(pageInfo);
    }

    @PostMapping("/resetPassword")
    public R<String> resetPassword(@RequestBody Map<String, Object> params) {
        return userService.resetPassword(params);
    }
}
